package com.pig4cloud.pig.common.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.pig4cloud.pig.common.core.servece.PigUser;
import com.pig4cloud.pig.common.core.util.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class PigTenantHandler implements TenantLineHandler {

	/**
	 * 忽略数据隔离表名列表
	 */
	private final List<String> tenantTable = Arrays.asList(
			//项目 业务模块表
			"tb_user", "tb_sheet_music","sys_role","sys_user" , "tb_stone_record", "tb_stone_log", "tb_stone_rank_config", "tb_stone_config",
			"tb_resources", "sys_dept", "sys_dict", "sys_dict_item", "sys_file", "sys_log", "sys_menu", "sys_oauth_client_details",
			"sys_post", "sys_public_param", "sys_role_menu", "sys_user_farm", "sys_user_post", "sys_user_role", "tb_address", "tb_category",
			"tb_collect", "tb_farm", "tb_order", "tb_order_detail", "tb_resource", "tb_review", "tb_user", "tb_strategy",
			//job 定时模块表
			"qrtz_blob_triggers", "qrtz_calendars", "qrtz_cron_triggers", "qrtz_fired_triggers", "qrtz_job_details", "qrtz_locks",
			"qrtz_paused_trigger_grps", "qrtz_scheduler_state", "qrtz_simple_triggers", "qrtz_simprop_triggers", "qrtz_triggers",
			"sys_job", "sys_job_log",
			//代码生成模块
			"gen_datasource_conf", "gen_field_type", "gen_group", "gen_table", "gen_template", "gen_template_group",
			"gen_table_column"
	);

	@Override
	public Expression getTenantId() {
		// 假设有一个租户上下文，能够从中获取当前用户的租户
		PigUser user = SecurityUtils.getUser();
		if (ObjectUtil.isNotEmpty(user)){
			String o = (String)user.getAttributes().get("tenantId");
			if (ObjectUtil.isNotEmpty(o)) {
			long tenantId = Long.parseLong(o);
			return new LongValue(tenantId);
			}else {
				return new NullValue();
			}
		}

		// 返回租户ID的表达式，LongValue 是 JSQLParser 中表示 bigint 类型的 class
		return new NullValue();
	}

	@Override
	public String getTenantIdColumn() {
		return "tenant_id";
	}

	@Override
	public boolean ignoreTable(String tableName) {
		// 根据需要返回是否忽略该表
		return tenantTable.contains(tableName);
	}

}
